/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-08-08 17:56:26
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-08-14 15:37:17
 * @FilePath: /lesson43/ClientCal.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "Socket.hpp"
#include <iostream>
#include <string>
#include <ctime>
#include <unistd.h>
#include <cassert>
#include "Protocol.hpp"
using namespace std;

void Usage(const string &proc)
{
    cout << "\nUsage: " << proc << " clientip clientport\n\n"
         << endl;
}

// ./clientcal clientip clientport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string clientip = argv[1];
    uint16_t clientport = stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(clientip, clientport);
    if (!r)
        return 1;

    string opers = "+-*/%=^&";
    srand(time(nullptr) ^ getpid());

    string inbuffer_stream;
    int cnt = 1;
    while (cnt <= 10)
    {
        cout << "第" << cnt << "次测试..." << endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100; // 0
        usleep(1234);

        char oper = opers[rand() % opers.size()];
        Request req(x, y, oper);
        req.DebugPrint();

        string pakg;
        req.Serialize(&pakg);

        pakg = Encode(pakg);

        cout << "这是最新发出去的请求：\n"<< pakg;

        write(sockfd.Fd(), pakg.c_str(), pakg.size());

        // cout << "这是最新发出去的请求：\n"<< pakg;
        // write(sockfd.Fd(), pakg.c_str(), pakg.size());
        // cout << "这是最新发出去的请求：\n"<< pakg;
        // write(sockfd.Fd(), pakg.c_str(), pakg.size());
        // cout << "这是最新发出去的请求：\n"<< pakg;

        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;

            cout << inbuffer_stream << endl;

            string text;
            bool r = Decode(inbuffer_stream, &text); // len"\n"result code\n
            assert(r);

            Response res;
            r = res.Deserialize(text); // result code
            assert(r);

            res.DebugPrint();

            cnt++;
            cout << "----------------------------------------------------------------------" << endl;
        } 
        sleep(1);
    }

    sockfd.Close();
    return 0;
}